<template>
  <el-drawer v-model="visible" title="编辑文章分类">
    <div class="edit-category">
      <el-form label-position="top" :model="modelValue" ref="formRef" :rules="rules">
        <el-form-item label="上级分类" prop="parent.id">
          <el-tree-select
            style="width: 100%"
            show-checkbox
            v-model="modelValue.parent!.id"
            :data="categories"
            check-strictly
            node-key="id"
            clearable
            :multiple="false"
            :props="{
              label: 'categoryName'
            }"
            :render-after-expand="false"
            check-on-click-node
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="modelValue.categoryName"></el-input>
        </el-form-item>
        <el-form-item label="分类编码" prop="categoryCode">
          <el-input v-model="modelValue.categoryCode"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  editArticleCategory,
  fetchArticleCategoryInfo,
  fetchArticleCategoryTrees,
  saveArticleCategory
} from "@/api/modules/article_category";
import { ResultEnum } from "@/enums/httpEnum";
import { ArticleCategorySchema } from "@/schema";
import { EmitProps } from "@/typings/interface";
import { isNotEmpty } from "@/utils/isHelper";
import { ElMessage, FormInstance } from "element-plus";
import { nextTick, reactive, ref, watch } from "vue";
const visible = ref(false);

const categories = ref();
const formRef = ref<FormInstance>();

const modelValue = reactive<ArticleCategorySchema>({
  categoryName: "",
  categoryCode: "",
  parent: { id: "" } as ArticleCategorySchema
});

const rules = {
  categoryName: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  categoryCode: [{ required: true, message: "分类编码不能为空", trigger: "blur" }]
};

const emits = defineEmits<EmitProps>();

function submit() {
  formRef.value?.validate().then(valid => {
    if (valid) {
      if (modelValue?.id) {
        edit();
      } else {
        save();
      }
    }
  });
}

function edit() {
  editArticleCategory({ id: modelValue?.id }, modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      emits("success");
      visible.value = false;
      ElMessage.success("编辑成功！");
    } else {
      ElMessage.error(message);
    }
  });
}

function save() {
  saveArticleCategory(modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      emits("success");
      visible.value = false;
      ElMessage.success("编辑成功！");
    } else {
      ElMessage.error(message);
    }
  });
}

function fetchTrees() {
  fetchArticleCategoryTrees().then(r => {
    const { code, data, message } = r;
    if (code === ResultEnum.SUCCESS) {
      categories.value = data.list ?? [];
    } else {
      ElMessage.error(message);
    }
  });
}

watch(
  () => visible.value,
  newVal => {
    if (!newVal) {
      nextTick(() => {
        formRef.value?.resetFields();
        if (modelValue.parent?.id) modelValue.parent.id = "";
      });
    }
  }
);

defineExpose({
  open(row: ArticleCategorySchema) {
    visible.value = true;
    fetchTrees();
    if (row?.id) {
      fetchArticleCategoryInfo({ id: row.id }).then(r => {
        const { code, data, message } = r;
        if (code === ResultEnum.SUCCESS) {
          Object.assign(modelValue, {
            ...data,
            parent: isNotEmpty(data.parent) ? data.parent : { id: "" }
          });
        } else {
          ElMessage.error(message);
        }
      });
    }
  }
});
</script>
